package com.msconfig.mvp.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.bean.deviceInfoBean.TagDeviceInfo;
import com.msconfig.bean.dialogBean.OperatorBean;
import com.msconfig.device.CommandParseManage;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.DeviceUpdateEvent;
import com.msconfig.event.GprsOperatorManagerOnClickItemEvent;
import com.msconfig.mvp.view.activity.base.BaseMvpActivity;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.VISIBLE;

public class SetupGprsFragment extends BaseMvpFragment implements View.OnClickListener {
    private FrameLayout flLoading;
    private ImageView ivLoading;
    private Animation setupAnim;
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private ImageView ivSwitchGprsOn;
    private ImageView ivSwitchGprsOff;
    private RelativeLayout rlOperators;
    private ConstraintLayout  clContent;
    private TextView tvOperationName;
    private ImageView ivSwitchMessageOn;
    private ImageView ivSwitchMessageOff;
    private Button btnDetermine;
    private OperatorBean mOperatorBean;
    private Context context;
    private TagDeviceInfo deviceInfo;
    private boolean isSetupDefail;
    private MyHandler myHandler;
    protected static final int MSG_SET_UP_DEFAIL =1;//设置失败


    //负责更新UI
    private static class MyHandler extends Handler {
        WeakReference<SetupGprsFragment> weakReference;
        private MyHandler(SetupGprsFragment fragment) {
            weakReference = new WeakReference<SetupGprsFragment>(fragment);
        }
        @Override
        public void handleMessage(Message msg) {
            SetupGprsFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_SET_UP_DEFAIL:
                        if(fragment.flLoading.getVisibility()==VISIBLE){//动画还在，说明设置事件过久设置失败
                            fragment.stopAnim();
                            fragment.isSetupDefail=true;
                            fragment.showToast(R.string.toast_setup_defail);
                        }
                        break;
                }
            }
        }
    }


    public static SetupGprsFragment newInstance() {
        Bundle args = new Bundle();
        SetupGprsFragment fragment = new SetupGprsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_setup_gprs;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);
        ivSwitchGprsOn = (ImageView)view.findViewById( R.id.iv_switch_gprs_on );
        ivSwitchGprsOff = (ImageView)view.findViewById( R.id.iv_switch_gprs_off );
        rlOperators = (RelativeLayout)view.findViewById( R.id.rl_title);
        tvOperationName = (TextView)view.findViewById( R.id.tv_operation_name );
        ivSwitchMessageOn = (ImageView)view.findViewById( R.id.iv_switch_message_on );
        ivSwitchMessageOff = (ImageView)view.findViewById( R.id.iv_switch_message_off);
        btnDetermine=(Button) view.findViewById(R.id.btn_determine);
        clContent=(ConstraintLayout) view.findViewById(R.id.cl_content);
        flLoading=view.findViewById(R.id.fl_loading);
        ivLoading = view.findViewById(R.id.iv_loading);
    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
        btnDetermine.setOnClickListener(this);
        ivSwitchGprsOn.setOnClickListener(this);
        ivSwitchGprsOff.setOnClickListener(this);
        ivSwitchMessageOn.setOnClickListener(this);
        ivSwitchMessageOff.setOnClickListener(this);
        rlOperators.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        tvCommonTitle.setText(R.string.title_setup_gprs);
        deviceInfo= CommandParseManage.getInstance().getDeviceInfo();
        if(ivSwitchGprsOff.getVisibility()==View.VISIBLE){
            clContent.setVisibility(View.GONE);
        }
    }


    //显示运营商信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showOperatorMessage(GprsOperatorManagerOnClickItemEvent event) {
        OperatorBean operatorBean=event.getOperatorBean();
        mOperatorBean=operatorBean;
        tvOperationName.setText(operatorBean.getOperator());
    }

    //GETALL成功
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showAnalysisGNSSDataSuccess(DeviceUpdateEvent.UpdateDialogGetRtkSuccessStatus event) {
        if(!DeviceManage.getInstance().isConnected())
            return;
        String apn;
        String apnName = "";
        if(deviceInfo.gprsInfo.mIsStartNet){
            onClickSwitchGprsOff();
        }else{
            onClickSwitchGprsOn();
        }
        apn=deviceInfo.gprsInfo.mApn;
        if(apn!=null){
            switch (apn) {
                case "CMNET":
                    apnName = getString(R.string.china_mobile);
                    break;
                case "3GNET":
                    apnName = getString(R.string.china_unicom);
                    break;
                case "":
                    if(deviceInfo.gprsInfo.mApnUser.equals(getString(R.string.china_telecom_apn_user)) && deviceInfo.gprsInfo.mApnPass.equals(getString(R.string.china_telecom_apn_pass))){
                        apnName = getString(R.string.china_telecom);
                    }else{
                        apnName = getString(R.string.china_other);
                    }
                    break;
                default:
                    apnName = getString(R.string.china_other);
                    break;
            }
        }
        tvOperationName.setText(apnName);
        if(deviceInfo.gprsInfo.mIsStartMessage){
            onClickSwitchMessageOff();
        }else{
            onClickSwitchMessageOn();
        }

    }

    //开始动画
    public void startAnim(){
        setupAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        setupAnim.setInterpolator(interpolator);
        if (setupAnim != null) {
            btnDetermine.setEnabled(false);
            flLoading.setVisibility(VISIBLE);
            ivLoading.startAnimation(setupAnim);  //开始动画
        }
    }

    //停止动画
    private void stopAnim() {
        if (setupAnim != null) {
            btnDetermine.setEnabled(true);
            setupAnim=null;
            flLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        }
    }

    //点击确定
    private void onClickDetermine() {
        isSetupDefail=false;
        String apnName;
        String apnUser;
        String apnPass;
        int mEnableNet;
        if(!DeviceManage.getInstance().isConnected()){
            Toast.makeText(context, R.string.toast_isdisconnect, Toast.LENGTH_SHORT).show();
            return;
        }

        if(ivSwitchGprsOn.getVisibility()== View.VISIBLE){
            mEnableNet =1;
        }else{
            mEnableNet =0;
        }
        int mEnableMessage;
        if(ivSwitchMessageOn.getVisibility()== View.VISIBLE){
            mEnableMessage =1;
        }else{
            mEnableMessage =0;
        }
        if(mOperatorBean==null){//没有选，直接用读取的
            apnName=deviceInfo.gprsInfo.mApn;
            apnUser=deviceInfo.gprsInfo.mApnUser;
            apnPass=deviceInfo.gprsInfo.mApnPass;
        }else{
            apnName=mOperatorBean.getName().substring(3);
            apnUser=mOperatorBean.getUser().substring(3);
            apnPass=mOperatorBean.getPass().substring(3);
        }
        //开始设置动画
        startAnim();
        //得到发送命令的集合
        ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getGprsCommandList(apnName, apnUser, apnPass, mEnableNet, mEnableMessage);
        //设置发送命令的集合
        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
        //开始发送命令
        CommandSendManage.getInstance().startSendCommand();

        //3s后判断有没有数据返回，没有代表设置失败
        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessageDelayed(MSG_SET_UP_DEFAIL,8000);
    }


    //设置全部命令成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setupAllCommandSucc(DeviceUpdateEvent.DeviceCommandSendStatus event) {
        if(isSetupDefail)//3s内没有得到消息显示设置失败，防止数据延迟之后回来设置成功
            return;
        if(event.getStatus()==2){//超时，发送失败
            stopAnim();
            Toast.makeText(context,event.getFunction()+"设置失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if(event.getStatus()==3){
            //有反馈信息回来
            stopAnim();
            Toast.makeText(context,R.string.toast_setup_success, Toast.LENGTH_SHORT).show();
            backTo();

            //最后再发送一次GETALL获取最新数据
            //得到发送命令的集合
            ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getGetAllCommandList();
            //设置发送命令额集合
            CommandSendManage.getInstance().setSendCommandList(sendCommandList);
            //开始发送命令
            CommandSendManage.getInstance().startSendCommand();
        }
    }


    @Override
    public void onClick(View v) {
        if(v==ivCommonBack){
            backTo();
        }else if(v==ivSwitchGprsOn){
            onClickSwitchGprsOn();
        }else if(v==ivSwitchGprsOff){
            onClickSwitchGprsOff();
        }else if(v==rlOperators){
            ((BaseMvpActivity)context).goToNextFragment(this, SetupGprsOperatorManagerFragment.newInstance());
        }else if(v==ivSwitchMessageOn){
            onClickSwitchMessageOn();
        }else if(v==ivSwitchMessageOff){
            onClickSwitchMessageOff();
        }else if(v==btnDetermine){
            onClickDetermine();
        }
    }

    private void onClickSwitchMessageOff() {
        ivSwitchMessageOn.setVisibility(View.VISIBLE);
        ivSwitchMessageOff.setVisibility(View.GONE);
    }

    private void onClickSwitchMessageOn() {
        ivSwitchMessageOn.setVisibility(View.GONE);
        ivSwitchMessageOff.setVisibility(View.VISIBLE);
    }

    private void onClickSwitchGprsOff() {
        ivSwitchGprsOff.setVisibility(View.GONE);
        ivSwitchGprsOn.setVisibility(View.VISIBLE);
        clContent.setVisibility(View.VISIBLE);
    }

    private void onClickSwitchGprsOn() {
        ivSwitchGprsOn.setVisibility(View.GONE);
        ivSwitchGprsOff.setVisibility(View.VISIBLE);
        clContent.setVisibility(View.GONE);
    }

    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }

    @Override
    public void onDestroy() {
        if(myHandler!=null){
            myHandler.removeCallbacksAndMessages(null);
            myHandler=null;
        }
        stopAnim();
        super.onDestroy();
    }

}
